package com.hqyj.shrio;


import com.hqyj.dao.EmployeeMapper;
import com.hqyj.pojo.Employee;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;


@Component
public class MyRealm extends AuthorizingRealm {
    @Autowired
    EmployeeMapper employeeMapper;

    //权限校验（判断）
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //1获取用户名(账号)
        String userName = principals.fromRealm(this.getName()).iterator().next() + "";
        //2查询认证用户拥有的角色
        List<String> listJobName = employeeMapper.selectJobNameByEName(userName);
        for (String s : listJobName) {
            System.out.println(userName + "拥有的职位是" + s);
        }

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(listJobName);
        return info;
    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //拿到数据库的用户名和密码 与前端token传过来的信息进行对比
        //1 获取令牌
        UsernamePasswordToken up = (UsernamePasswordToken) token;
        //2取出用户名
        String s = up.getPrincipal() + "";

        //3验证用户是否正确
        Employee employee = new Employee();
        employee.seteName(s);
        Employee yh = employeeMapper.select(employee);
        if (yh == null) {
            //通过抛出异常的方式将信息传递到service层
            throw new UnknownAccountException();
        }

        //校对密码
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(yh.geteName(), yh.getePwd(), new Md5Hash(s), this.getName());

        return authenticationInfo;

    }
}
